package action;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;

import model.ShortInformationBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import web.action.Action;

import agent.SearchAgent;

@SuppressWarnings("serial")
public class AjaxToJson extends Action {

	private static final String GENERATE_RESULT = "generate";

	private String what;
	private String q;
	private int limit;
	private Set<ShortInformationBean> result;

	public String getWhat() {
		return what;
	}

	public void setWhat(String what) {
		this.what = what;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getMaxResult() {
		return limit;
	}

	public String getQ() {
		return q;
	}

	public void setQ(String q) {
		if (q != null) {
			q = unescape(q.trim());
			this.q = q;
		}
	}

	public Set<? extends ShortInformationBean> getResult() {
		return result;
	}

	public String execute() throws JSONException {

		result = new LinkedHashSet<ShortInformationBean>();

		if ("searchAlbums".equals(what)) {
			Collection<ShortInformationBean> albums = SearchAgent.getSole().searchAlbum(q.trim(), limit);
			result.addAll(albums);
		}

		return GENERATE_RESULT;
	}

	public String getJsonResult() throws JSONException {
		JSONArray jsonArray = new JSONArray();
		for (Object o : this.result) {
			JSONObject jo = new JSONObject();

			ShortInformationBean sib = (ShortInformationBean) o;
			
			jo.put("id", sib.getId());
			jo.put("value", sib.getName());
			jo.put("info", sib.getDescription());
			
			jsonArray.put(jo);
		}
		
		return jsonArray.toString(5);
	}
}
